package io.zcoder.innoway.activities;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.util.Log;
import android.view.View;
import android.widget.Switch;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.Scopes;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.Scope;
import com.google.android.gms.fitness.Fitness;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnCheckedChanged;
import butterknife.OnClick;
import io.zcoder.innoway.R;
import io.zcoder.innoway.commons.Constants;
import io.zcoder.innoway.commons.PrefUtils;
import io.zcoder.innoway.models.ResponseBase;
import io.zcoder.innoway.rest.RestClient;
import io.zcoder.innoway.widgets.TextViewCustom;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;

public class UserSettingActivity extends BaseActivity {

    @BindView(R.id.reset)
    TextViewCustom mReset;

    @BindView(R.id.sw_google_fit)
    Switch mSwGoogleFit;

    @BindView(R.id.sw_fitbit)
    Switch mSwFitbit;

    @OnClick(R.id.change_password)
    void changePass() {
        startActivity(new Intent(this, ChangePassWordActivity.class));
    }

    @OnClick(R.id.about_us)
    void aboutUs() {
        startActivity(new Intent(this, AboutUsActivity.class));
    }

    @OnClick(R.id.reset)
    void reset() {
        new MaterialDialog.Builder(UserSettingActivity.this)
                .title(R.string.reset)
                .content(R.string.are_you_sure)
                .positiveText(R.string.yes)
                .negativeText(R.string.no)
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        resetUser();
                    }
                }).show();
    }

    @OnCheckedChanged(R.id.sw_fitbit)
    void onFitbitChange(Switch swFitbit)
    {

    }

    @OnCheckedChanged(R.id.sw_google_fit)
    void onGoogleFitChange(Switch swGoogleFit)
    {
        // Create the Google API Client
        if (mClient == null) {
            mClient = new GoogleApiClient.Builder(this)
                    .addApi(Fitness.HISTORY_API)
                    .addScope(new Scope(Scopes.FITNESS_ACTIVITY_READ_WRITE))
                    .addConnectionCallbacks(
                            new GoogleApiClient.ConnectionCallbacks() {
                                @Override
                                public void onConnected(Bundle bundle) {
                                    Log.i(TAG, "Connected!!!");
                                    PrefUtils.setInt(UserSettingActivity.this, PrefUtils.PREF_GOOGLE_FIT_STATUS, 1);
                                }

                                @Override
                                public void onConnectionSuspended(int i) {
                                    // If your connection to the sensor gets lost at some point,
                                    // you'll be able to determine the reason and react to it here.
                                    if (i == GoogleApiClient.ConnectionCallbacks.CAUSE_NETWORK_LOST) {
                                        Log.i(TAG, "Connection lost.  Cause: Network Lost.");
                                    } else if (i == GoogleApiClient.ConnectionCallbacks.CAUSE_SERVICE_DISCONNECTED) {
                                        Log.i(TAG, "Connection lost.  Reason: Service Disconnected");
                                    }
                                }
                            }
                    )
                    .enableAutoManage(this, 0, new GoogleApiClient.OnConnectionFailedListener() {
                        @Override
                        public void onConnectionFailed(ConnectionResult result) {
                            Log.i(TAG, "Google Play services connection failed. Cause: " +
                                    result.toString());

                        }
                    })
                    .build();
        } else {
            if (swGoogleFit.isChecked()) {
                mClient.connect();
            } else {
                mClient.disconnect();
            }
        }
    }

    public static GoogleApiClient mClient = null;
    private static final String TAG = "auth_state_pending";
    private static final String AUTH_PENDING = "auth_state_pending";
    private static boolean authInProgress = false;



    @OnClick(R.id.sign_out)
    void logout() {
        new MaterialDialog.Builder(UserSettingActivity.this)
                .title(R.string.sign_out)
                .content(R.string.are_you_sure)
                .positiveText(R.string.yes)
                .negativeText(R.string.no)
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        signOut();
                    }
                }).show();
    }

    @OnClick(R.id.feedback)
    public void onFeedback() {
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("message/rfc822");
        intent.putExtra(Intent.EXTRA_EMAIL, new String[]{getString(R.string.email_support)});
        intent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.feedback));
        startActivity(intent);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_user_setting_activity);
        ButterKnife.bind(this);
        setTitle(getString(R.string.user_settings));
        showBack(true);
        boolean mainProfile = getIntent().getBooleanExtra(Constants.IS_MAIN_PROFILE_EXTRAS, false);
        if (mainProfile) {
            mReset.setVisibility(View.VISIBLE);
        } else {
            mReset.setVisibility(View.VISIBLE);
        }
    }

    private void resetUser() {
        showProgress();
        RestClient.build(this, true).resetUser(new Callback<ResponseBase>() {
            @Override
            public void success(ResponseBase responseBase, Response response) {
                if (responseBase.getStatus_code() != 200) {
                    showAlert(getString(R.string.error), responseBase.getMessage());
                }
                hideProgress();
                Intent intent = new Intent(UserSettingActivity.this, TopActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
                startActivity(intent);
                finish();
            }

            @Override
            public void failure(RetrofitError error) {
                hideProgress();
            }
        });
    }

    private void signOut() {
        showProgress();
        RestClient.build(this, true).logout(1, PrefUtils.getString(this, PrefUtils.PREF_AUTHEN_TOKEN), new Callback<ResponseBase>() {
            @Override
            public void success(ResponseBase responseBase, Response response) {
                if (responseBase.getStatus_code() != 200) {
                    showAlert(getString(R.string.error), responseBase.getMessage());
                }
                hideProgress();
                Intent intent = new Intent(UserSettingActivity.this, LoginActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                startActivity(intent);
            }

            @Override
            public void failure(RetrofitError error) {
                hideProgress();
            }
        });
    }

}
